#include"../source/server.hpp"
#include"../source/Socket.hpp"
#include<unordered_map>
uint64_t conn_id = 0;   
std::unordered_map<uint64_t,PtrConnection> _conns;    
void ConnectionDestory(const PtrConnection &conn){
    _conns.erase(conn->Id());
    lg(Info,"Connection Destory:%p",conn.get());
}

void OnConnected(const PtrConnection &conn){
    lg(Info,"Connection Established:%p",conn.get());
}

void HandleEvent(const PtrConnection &conn){    
    std::cout<<"event:"<<conn->Id()<<std::endl;
}

void OnMessage(const PtrConnection &conn, Buffer *buf){
    lg(Info,"%s",buf->ReadPosition());
    buf -> MoveReadOffset(buf->ReadAbleSize());
    std::string str = "server hello World";
    conn->Send(str.c_str(),str.size());
    // conn->Shutdown();//调用关闭Connection
}

void Accepter(EventLoop *loop,Channel *lst_channel){
    int fd = lst_channel->Fd();
    int newfd = accept(fd,NULL,NULL);    
    if(newfd < 0) return;
    conn_id++;
    PtrConnection conn(new Connection(loop,conn_id,newfd)); 
    std::cout<<"Onmessage地址:"<<(void *)OnMessage<<std::endl;
    conn->SetMessageCallback(OnMessage);    
    conn->SetConectedCallback(std::bind(OnConnected,std::placeholders::_1));
    conn->SetSvrConectedCallback(std::bind(ConnectionDestory,std::placeholders::_1));  
    conn->SetAnyEventCallback(std::bind(HandleEvent,std::placeholders::_1));  

    // conn->SetAnyEventCallback();   
    conn->EnabelInactiveRelease(10); 
    conn->Established(); //就绪序列化
    _conns.insert(std::make_pair(conn_id,conn));
}

int main(){ //先实现一个EventLoop,
    Socket TCP_Server;
    TCP_Server.CreateServer(8888);
    EventLoop _loop;
    std::cout<<"TCP_Server.Fd():"<<TCP_Server.Fd()<<std::endl;
    Channel _channel(&_loop,TCP_Server.Fd());
    //创建channel,并添加监控?在哪里添加监控？
    _channel.SetReadCallback(std::bind(Accepter,&_loop,&_channel)); 
    _channel.EnableRead();    
    // while(1){
        _loop.Start();//在这个里面一致循环，sleep(1)没有意义
    // }
    return 0;
}